import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import ViewUI from 'view-design'
import {getToken,setToken} from '@/libs/util'
import config from '@/config'
const { homeName } = config

Vue.use(Router)
//获取原型对象上的push函数
const originalPush = Router.prototype.push
//修改原型对象中的push方法
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

const router = new Router({
    routes,
    mode:'history'
})

const LOGIN_PAGE_NAME ='login'

const turnTo = (to,access,next)=>{

}

router.beforeEach((to,from,next)=>{
    // 开始加载进度条
    ViewUI.LoadingBar.start();
    next()
    const token = getToken()
    if(!token && to.name!==LOGIN_PAGE_NAME){
        // 未登录且要跳转的页面不是登录页
        next({
            name:LOGIN_PAGE_NAME // 跳转到登录页
        })
    }else if (!token && to.name===LOGIN_PAGE_NAME){
        // 未登陆且要跳转的页面是登录页
        next()
    }else if (token && to.name===LOGIN_PAGE_NAME){
        // 已登录且要跳转的页面是登录页
        next({
            name:homeName // 跳转到homeName页
        })
    }else{
        // todo
    }
})

router.afterEach(to => {
    // 设置标题
    // todo
    ViewUI.LoadingBar.finish()
    window.scrollTo(0,0)
})


export default router